package com.adobe.lc.customservices;

import java.io.StringReader;
import java.io.Reader;
import java.util.List;
import org.drools.RuleBase;
import org.drools.RuleBaseFactory;
import org.drools.StatelessSession;
import org.drools.StatelessSessionResult;
import org.drools.base.CopyIdentifiersGlobalExporter;
import org.drools.compiler.PackageBuilder;
import org.drools.rule.Package;

/**
 *
 * @author bartek
 */
public class RulesServiceImpl implements RulesService
{
    public RulesServiceImpl()
    {
    }

    public String applyRules(String rules, List facts)
    {
        RulesResult result = new RulesResult();

        try
        {
            Reader source = new StringReader(rules);

            PackageBuilder builder = new PackageBuilder();
            builder.addPackageFromDrl(source);

            if (builder.hasErrors())
            {
                System.out.println(builder.getErrors().toString());
            }

            Package pkg = builder.getPackage();
            RuleBase ruleBase = RuleBaseFactory.newRuleBase();
            ruleBase.addPackage(pkg);

            StatelessSession session = ruleBase.newStatelessSession();
            session.setGlobalExporter(new CopyIdentifiersGlobalExporter());
            session.setGlobal("result", result);

            StatelessSessionResult sr = session.executeWithResults(facts);
            result = (RulesResult) sr.getGlobal("result");
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
        finally
        {
            return result.getMessage();
        }
    }
}